import React, { useState, useEffect } from 'react';
import { Card, Button, Space, message, Typography, Progress, Modal, Row, Col } from 'antd';
import { DownloadOutlined, DatabaseOutlined, ExclamationCircleOutlined } from '@ant-design/icons';
import { dataAPI } from '../services/api';
import apiClient from '../services/api';

const { Title, Text } = Typography;
const { confirm } = Modal;

interface FundListProgress {
  total: number;
  downloaded: number;
  status: 'idle' | 'downloading' | 'completed' | 'error';
}

interface FundDetailProgress {
  total: number;
  downloaded: number;
  percentage: number;
  status: 'idle' | 'downloading' | 'completed' | 'error';
}

const FundDataDownload: React.FC = () => {
  const [fundListLoading, setFundListLoading] = useState(false);
  const [fundDetailLoading, setFundDetailLoading] = useState(false);
  const [fundListCount, setFundListCount] = useState(0);
  const [fundDetailCount, setFundDetailCount] = useState(0);
  const [currentTaskId, setCurrentTaskId] = useState<number | null>(null);
  const [fundListProgress, setFundListProgress] = useState<FundListProgress>({
    total: 0,
    downloaded: 0,
    status: 'idle'
  });
  const [fundDetailProgress, setFundDetailProgress] = useState<FundDetailProgress>({
    total: 0,
    downloaded: 0,
    percentage: 0,
    status: 'idle'
  });

  // 检查数据库数据
  const checkDatabaseData = async () => {
    try {
      const response = await dataAPI.checkDatabaseData();
      return response;
    } catch (error) {
      console.error('检查数据库数据失败:', error);
      throw error;
    }
  };

  // 清空数据库数据
  const clearDatabaseData = async (dataType: string) => {
    try {
      const response = await dataAPI.clearFundData(dataType);
      return response;
    } catch (error) {
      console.error('清空数据库数据失败:', error);
      throw error;
    }
  };

  // 显示删除确认弹框
  const showDeleteConfirm = (dataType: string, existingCount: number, onConfirm: () => void, onCancel?: () => void) => {
    const dataTypeName = dataType === 'fund_list' ? '基金列表' : '基金详细信息';
    confirm({
      title: '数据已存在',
      icon: <ExclamationCircleOutlined />,
      content: (
        <div>
          <p>数据库中已存在 <strong>{existingCount}</strong> 条{dataTypeName}数据。</p>
          <p>是否删除现有数据并重新下载？</p>
          <p style={{ color: '#ff4d4f', fontSize: '12px' }}>注意：删除操作不可恢复</p>
        </div>
      ),
      okText: '删除并重新下载',
      cancelText: '取消',
      okType: 'danger',
      onOk: onConfirm,
      onCancel: () => {
        message.info('已取消下载');
        if (onCancel) {
          onCancel();
        }
      }
    });
  };

  // 下载基金列表
  const handleDownloadFundList = async () => {
    const dbData = await checkDatabaseData();
    const hasData = dbData.data.fund_list.has_data;
    
    const doDownload = async () => {
      setFundListLoading(true);
      setFundListProgress({ total: 0, downloaded: 0, status: 'downloading' });
      
      try {
        const response = await dataAPI.downloadFundList({ fund_type: 'all' });
        if (response.status === 'success') {
          const savedCount = response.data?.total_saved || response.data?.saved_count || response.data?.total_downloaded || 0;
          setFundListCount(savedCount);
          setFundListProgress({
            total: savedCount,
            downloaded: savedCount,
            status: 'completed'
          });
          message.success(`基金列表下载完成，共下载 ${savedCount} 条基金信息`);
        } else {
          throw new Error(response.message || '下载失败');
        }
      } catch (error: any) {
        console.error('下载基金列表失败:', error);
        message.error(error.message || '下载基金列表失败');
        setFundListProgress(prev => ({ ...prev, status: 'error' }));
      } finally {
        setFundListLoading(false);
      }
    };

    if (hasData) {
      showDeleteConfirm('fund_list', dbData.data.fund_list.count || 0, async () => {
        const cleared = await clearDatabaseData('fund_list');
        if (cleared) {
          await doDownload();
        }
      });
    } else {
      await doDownload();
    }
  };

  // 下载基金详细信息
  const handleDownloadFundDetail = async () => {
    const dbData = await checkDatabaseData();
    const hasData = dbData.data.fund_details.has_data;
    
    const doDownload = async () => {
      setFundDetailLoading(true);
      setFundDetailProgress({ total: 0, downloaded: 0, percentage: 0, status: 'downloading' });
      
      try {
        // 启动下载任务（强制更新）
        const response = await dataAPI.downloadFundDetails(true);
        
        if (response.status === 'success') {
          // 保存任务ID（如果后端返回了任务ID）
          if (response.data?.task_id) {
            setCurrentTaskId(response.data.task_id);
          }
          // 开始轮询进度
          let pollRetryCount = 0;
          const maxPollRetries = 10; // 最大重试次数
          
          const pollProgress = async () => {
            try {
              const progressResponse = await dataAPI.getDownloadProgress();
              if (progressResponse.status === 'success') {
                pollRetryCount = 0; // 重置重试计数
                const fundDetailData = progressResponse.data.fund_detail;
                const percentage = fundDetailData.total > 0 ? Math.round((fundDetailData.downloaded / fundDetailData.total) * 100) : 0;
                
                setFundDetailProgress({
                  total: fundDetailData.total,
                  downloaded: fundDetailData.downloaded,
                  percentage: percentage,
                  status: fundDetailData.status
                });
                
                if (fundDetailData.status === 'completed' || percentage >= 100) {
                  setFundDetailCount(fundDetailData.downloaded);
                  message.success(`基金详细信息下载完成，共下载 ${fundDetailData.downloaded} 条基金详细信息`);
                  setFundDetailLoading(false);
                  setCurrentTaskId(null);
                  return;
                } else if (fundDetailData.status === 'error') {
                  setCurrentTaskId(null);
                  throw new Error('下载任务失败');
                } else if (fundDetailData.status === 'cancelled') {
                  setFundDetailLoading(false);
                  setCurrentTaskId(null);
                  message.info('下载任务已被取消');
                  return;
                }
                
                // 继续轮询
                setTimeout(pollProgress, 1000);
              }
            } catch (error) {
              console.error('获取下载进度失败:', error);
              pollRetryCount++;
              
              if (pollRetryCount >= maxPollRetries) {
                setFundDetailLoading(false);
                setCurrentTaskId(null);
                message.error('网络连接失败，请检查网络后重试');
                return;
              }
              
              // 网络错误时继续轮询，不中断下载流程
              setTimeout(pollProgress, 2000); // 延长轮询间隔到2秒
            }
          };
          
          // 开始轮询
          setTimeout(pollProgress, 1000);
        } else {
          throw new Error(response.message || '启动下载失败');
        }
      } catch (error: any) {
        console.error('下载基金详细信息失败:', error);
        // 检查是否是成功消息被误判为错误
        const errorMessage = error.response?.data?.message || error.message || '下载基金详细信息失败';
        
        if (errorMessage.includes('基金详细信息更新完成')) {
          // 获取最终的下载统计
          try {
            const finalResponse = await dataAPI.getDownloadProgress();
            if (finalResponse.status === 'success') {
              const finalProgress = finalResponse.data;
              setFundDetailProgress({
                total: finalProgress.total,
                downloaded: finalProgress.completed,
                percentage: 100,
                status: 'completed'
              });
              setFundDetailCount(finalProgress.completed);
              message.success(`基金详细信息下载完成，共下载 ${finalProgress.completed} 条基金详细信息`);
            } else {
              setFundDetailProgress(prev => ({ ...prev, status: 'completed' }));
              message.success('基金详细信息下载完成');
            }
          } catch (progressError) {
            setFundDetailProgress(prev => ({ ...prev, status: 'completed' }));
            message.success('基金详细信息下载完成');
          }
        } else {
          message.error(errorMessage);
          setFundDetailProgress(prev => ({ ...prev, status: 'error' }));
        }
        setFundDetailLoading(false);
        setCurrentTaskId(null);
      }
    };

    if (hasData) {
      showDeleteConfirm('fund_detail', dbData.data.fund_details.count || 0, async () => {
        const cleared = await clearDatabaseData('fund_details');
        if (cleared) {
          await doDownload();
        }
      }, async () => {
        // 用户点击取消时，如果有正在运行的任务，停止它
        if (currentTaskId) {
          try {
            await dataAPI.stopDownloadTask(currentTaskId);
            setCurrentTaskId(null);
            setFundDetailLoading(false);
            setFundDetailProgress(prev => ({ ...prev, status: 'idle' }));
            message.info('已停止下载任务');
          } catch (error) {
            console.error('停止任务失败:', error);
          }
        }
      });
    } else {
      await doDownload();
    }
  };

  // 组件加载时获取当前数据统计
  useEffect(() => {
    const fetchData = async () => {
      try {
        const response = await dataAPI.getDownloadProgress();
        if (response.status === 'success') {
          const data = response.data;
          setFundListCount(data.fund_list?.downloaded || 0);
          setFundDetailCount(data.fund_detail?.downloaded || 0);
          
          // 设置基金详细信息进度
          const fundDetailData = data.fund_detail;
          if (fundDetailData) {
            setFundDetailProgress({
              total: fundDetailData.total,
              downloaded: fundDetailData.downloaded,
              percentage: fundDetailData.total > 0 ? Math.round((fundDetailData.downloaded / fundDetailData.total) * 100) : 0,
              status: fundDetailData.status
            });
          }
        }
      } catch (error) {
        console.error('获取数据统计失败:', error);
      }
    };
    
    fetchData();
  }, []);

  return (
    <div style={{ padding: '24px' }}>
      <Title level={2}>基金信息下载</Title>
      
      <Row gutter={[24, 24]}>
        {/* 基金列表下载 */}
        <Col xs={24} lg={12}>
          <Card
            title="基金列表下载"
            extra={<DatabaseOutlined />}
            style={{ height: '100%' }}
          >
            <Space direction="vertical" style={{ width: '100%' }} size="large">
              <Text type="secondary">
                下载所有基金的基本列表信息，包括基金代码、基金名称等。
              </Text>
              
              {fundListCount > 0 && (
                <div>
                  <Text strong>当前已下载：</Text>
                  <Text type="success">{fundListCount} 条基金信息</Text>
                </div>
              )}
              
              <Button
                type="primary"
                icon={<DownloadOutlined />}
                loading={fundListLoading}
                onClick={handleDownloadFundList}
                size="large"
                block
              >
                {fundListLoading ? '下载中...' : '下载基金列表'}
              </Button>
              
              {fundListProgress.status === 'downloading' && (
                <div>
                  <Text>正在下载基金列表...</Text>
                  {fundListProgress.total > 0 && (
                    <Progress 
                      percent={Math.round((fundListProgress.downloaded / fundListProgress.total) * 100)}
                      status="active"
                      format={() => `${fundListProgress.downloaded}/${fundListProgress.total}`}
                    />
                  )}
                </div>
              )}
              
              {fundListProgress.status === 'completed' && (
                <div>
                  <Progress percent={100} status="success" />
                  <Text type="success">✓ 下载完成，共 {fundListProgress.downloaded} 条基金信息</Text>
                </div>
              )}
              
              {fundListProgress.status === 'error' && (
                <div>
                  <Progress percent={fundListProgress.total > 0 ? Math.round((fundListProgress.downloaded / fundListProgress.total) * 100) : 0} status="exception" />
                  <Text type="danger">✗ 下载失败，请重试</Text>
                </div>
              )}
            </Space>
          </Card>
        </Col>
        
        {/* 基金详细信息下载 */}
        <Col xs={24} lg={12}>
          <Card
            title="基金详细信息下载"
            extra={<DatabaseOutlined />}
            style={{ height: '100%' }}
          >
            <Space direction="vertical" style={{ width: '100%' }} size="large">
              <Text type="secondary">
                下载基金的详细信息，包括基金经理、投资策略、业绩基准等。
              </Text>
              
              <Button
                type="primary"
                icon={<DownloadOutlined />}
                loading={fundDetailLoading}
                onClick={handleDownloadFundDetail}
                size="large"
                block
              >
                {fundDetailLoading ? '下载中...' : '下载基金详细信息'}
              </Button>
              
              <Button 
                onClick={() => {
                  setFundDetailProgress({ total: 0, downloaded: 0, percentage: 0, status: 'idle' });
                  setFundDetailCount(0);
                }} 
                disabled={fundDetailLoading}
                size="large"
                block
                style={{ marginTop: 8 }}
              >
                重置进度
              </Button>
              
              {fundDetailLoading && (
                <div>
                  <Text>正在下载基金详细信息...</Text>
                  {fundDetailProgress.total > 0 && (
                    <Progress 
                      percent={fundDetailProgress.percentage}
                      status="active"
                      format={() => `${fundDetailProgress.downloaded}/${fundDetailProgress.total}`}
                    />
                  )}
                </div>
              )}
              
              {fundDetailProgress.status === 'completed' && (
                <div>
                  <Progress percent={100} status="success" />
                  <Text type="success">✓ 下载完成，共 {fundDetailProgress.downloaded} 条详细信息</Text>
                </div>
              )}
              
              {fundDetailProgress.status === 'error' && (
                <div>
                  <Progress 
                    percent={fundDetailProgress.total > 0 ? Math.round((fundDetailProgress.downloaded / fundDetailProgress.total) * 100) : 0} 
                    status="exception" 
                  />
                  <Text type="danger">✗ 下载失败，请重试</Text>
                </div>
              )}
            </Space>
          </Card>
        </Col>
      </Row>
    </div>
  );
};

export default FundDataDownload;